<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import Note from '@/components/notify'
import Msg from '@/components/message'
import { upImgApi, upVideoApi } from '@/common/api'

// 定义父组件传来的参数
const props = defineProps({
  contents: { //每页显示条数
    type: String,
    default: '',
    required: true
  }
})

// 定义父组件调用子组件的方法
const emits = defineEmits(['setContents'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
// 内容 HTML
const htmlStr = ref('')

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const toolbarConfig = {}
const editorConfig = {placeholder: '请输入内容...', MENU_CONF: {}}
editorConfig.MENU_CONF['uploadImage'] = {
  fieldName: 'upImg',
  async customUpload(file, insertFn) {
    let formData = new FormData()
    formData.append('upImg', file)
    const res = await upImgApi(formData)
    if (res.errno === 0) {
      const alt = res.data.name
      const url = res.data.url
      insertFn(url, alt, url)
      Note({kind: 'success', title: '成功', txt: '文件上传成功！'})
    } else {
      Msg({kind: 'error', txt: res.message})
    }
  }
}
editorConfig.MENU_CONF['uploadVideo'] = {
  fieldName: 'upVideo',
  async customUpload(file, insertFn) {
    let formData = new FormData()
    formData.append('upVideo', file)
    const res = await upVideoApi(formData)
    if(res.errno === 0) {
      const url = res.data.url
      insertFn(url, '')
      Note({kind: 'success', title: '成功', txt: '文件上传成功！'})
    } else {
      Msg({kind: 'error', txt: res.message})
    }
  }
}

onMounted(() => {
  setTimeout(() => {
    htmlStr.value = props.contents
  }, 200)
})

const setContents = () => {
  emits('setContents', htmlStr.value)
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<template>
  <div class="we-a">
    <Toolbar class="we-b" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="htmlStr" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onBlur="setContents" />
  </div>
</template>

<style scoped>
.we-a {border: 1px solid #CCC;}
.we-b {border-bottom: 1px solid #CCC;}
</style>
